package com.cbd.controller;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Window;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cbd.pojo.Complaintrecord;
import com.cbd.pojo.Landlady;
import com.cbd.pojo.PageBean;
import com.cbd.pojo.Personalcarport;
import com.cbd.pojo.Purpose;
import com.cbd.pojo.Record;
import com.cbd.pojo.RentInfo;
import com.cbd.pojo.Renter;
import com.cbd.pojo.User;
import com.cbd.service.ComplaintrecordService;
import com.cbd.service.LandladyService;
import com.cbd.service.PurposeService;
import com.cbd.service.RecordService;
import com.cbd.util.IQuantity;

@Controller
public class LandladyController {
	
	
	@Resource(name="landladyServiceImpl")
	private LandladyService landladyService;
	@Resource(name="purposeServiceImpl")
	private PurposeService purposeService;
	@Resource(name="recordServiceImpl")
	private RecordService recordService;
	@Resource(name="complaintrecordServiceImpl")
	private ComplaintrecordService cs;
	@RequestMapping("landladyRegist")
	public String landladyRegist(Landlady landlady){
		try {
			landladyService.regist(landlady);
			return "redirect:login.jsp";
		} catch (Exception e) {
			// TODO: handle exception
			return "error";
		}
		
		
	}
	@RequestMapping("findLadyByCard")
	public @ResponseBody Landlady findLadyByCard(String card){
		Landlady landlady =landladyService.findLadyByCard(card);
		if(landlady!=null){
			landlady.setUser(null);
			landlady.setPersonalcarport(null);
		}
		return landlady;
	}
	@RequestMapping({"authCode"})
    public void getAuthCode(HttpServletRequest request, HttpServletResponse response,HttpSession session)
            throws IOException {
        int width = 67;
        int height = 27;
        Random random = new Random();
        //设置response头信息
        //禁止缓存
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("", "");
        //生成缓冲区image类
        BufferedImage image = new BufferedImage(width, height, 1);
        //产生image类的Graphics用于绘制操作
        Graphics g = image.getGraphics();
        //Graphics类的样式
        g.setColor(this.getRandColor(200, 250));
        g.setFont(new Font("Times New Roman",0,28));
        g.fillRect(0, 0, width, height);
        //绘制干扰线
        for(int i=0;i<40;i++){
            g.setColor(this.getRandColor(130, 200));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int x1 = random.nextInt(12);
            int y1 = random.nextInt(12);
            g.drawLine(x, y, x + x1, y + y1);
        }

        //绘制字符
        String strCode = "";
        for(int i=0;i<4;i++){
            String rand = String.valueOf(random.nextInt(10));
            strCode = strCode + rand;
            g.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));
            g.drawString(rand, 13*i+6, 28);
        }

        //将字符保存到session中用于前端的验证
       
        g.dispose();
        ImageIO.write(image, "JPEG", response.getOutputStream());
        response.getOutputStream().flush();
        session.setAttribute("strCode", strCode);
    } 
	 Color getRandColor(int fc,int bc){
	        Random random = new Random();
	        if(fc>255)
	            fc = 255;
	        if(bc>255)
	            bc = 255;
	        int r = fc + random.nextInt(bc - fc);
	        int g = fc + random.nextInt(bc - fc);
	        int b = fc + random.nextInt(bc - fc);
	        return new Color(r,g,b);
	    }
	 @RequestMapping("getAuthCode")
	 public void getAuthCode(PrintWriter pw ,HttpSession session){
		 pw.print(session.getAttribute("strCode").toString());
	 }
	@RequestMapping(path="cbd/landlady/publishInfo")
	public String publishInfo(HttpServletRequest req) throws ParseException{
		RentInfo info = new RentInfo();
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		info.setStartTime(sd.parse(req.getParameter("startTime")));
		info.setEndTime(sd.parse(req.getParameter("endTime")));
		info.setCreateTime(new Date());
		info.setType(true);
		BigDecimal bd= new BigDecimal(req.getParameter("price"));
		System.out.println(bd);
		info.setPrice(bd);
		Personalcarport p = new Personalcarport();
		p.setCarportID(Integer.parseInt(req.getParameter("carPortID")));
		info.setPersonalcarport(p);
		landladyService.publishRentInfo(info);
		return "redirect:myCarPort.jsp";
		
	}
	@RequestMapping(path="cbd/landlady/showAboutThisRentInfo")
	public@ResponseBody PageBean showAboutThisRentInfo(String id,String curPage){
		PageBean page = new PageBean();
		page.setCurPage(Integer.parseInt(curPage));
		page.setPageSize(IQuantity.pageSize);
		page = purposeService.findPurposeByInfoId(page, Integer.parseInt(id));
//		Purpose p = (Purpose) page.getList().get(0);
//		RentInfo r = p.getRentInfo();
//		System.out.println(r.getPersonalcarport().getCarportAddress()+r.getPersonalcarport().getCarNO());
//		System.out.println(r.getStartTime());
//		System.out.println(p.getNote());
//		Renter r1 = p.getRenter();
//		System.out.println(r1.getRenterAddress());
		List<Purpose> list = (List<Purpose>) page.getList();
		for (Purpose p : list) {
			
		}
		return page;
		
	}

	@RequestMapping(path="updateLandlady")
	public String updateLandlady(HttpServletRequest req){
		String tiao="";
		Landlady landLady=new Landlady();
		User user=new User();
		user.setUserPWD(req.getParameter("userPWD"));
		landLady.setLadyTel(req.getParameter("ladyTel"));
		landLady.setLadyAddress(req.getParameter("ladyAddress"));
		landLady.setLadyDescribe(req.getParameter("ladyDescribe"));
		int id=(int) req.getSession().getAttribute("id");
		landLady.setUser(user);
		int count= landladyService.updateLandlady(landLady, id);
		System.out.println(count);
		if(count==2){
			tiao="redirect:cbd/landlady/welcome.jsp";
		}else{
			tiao="redirect:cbd/landlady/updateMyInfo.jsp";
		}
		return tiao;
	}
	@RequestMapping(path="showlandLady.do")
	public @ResponseBody Landlady showlandLady(HttpServletRequest req){
		int id= Integer.parseInt(req.getParameter("id"));
		req.getSession().setAttribute("id", id);
		Landlady lady = landladyService.findLandladyByLadyID(id);
		lady.setPersonalcarport(null);
		return lady;
		
	}
	@RequestMapping(path="cbd/landlady/agreeToRentCarPort")
	public void agreeToRentCarPort(String carPortID,String renterID,String ladyID,String purposeID,String rentInfoID,PrintWriter pw){
		//System.out.println(carPortID+"----"+renterID+"----"+ladyID+"----"+purposeID+"----"+rentInfoID);
		landladyService.agreeRentCarPort(Integer.parseInt(carPortID), Integer.parseInt(renterID), Integer.parseInt(ladyID), Integer.parseInt(purposeID), Integer.parseInt(rentInfoID));
		pw.print("");
		
	}
	@RequestMapping(path="cbd/landlady/showAllHistory")
	public@ResponseBody PageBean showAllHistory(String curPage,String ladyID){
		//System.out.println(curPage+"----"+ladyID);
		int curPages = Integer.parseInt(curPage);
		int ladyId = Integer.parseInt(ladyID);
		PageBean page = new PageBean();
		page.setCurPage(curPages);
		page.setPageSize(IQuantity.pageSize);
		page = recordService.findAllRecord(ladyId, page);
		List<Record> list = (List<Record>) page.getList();
		for (Record r : list) {
			Purpose p = r.getPurpose();
			p.setRecord(null);
			p.getRenter().setUser(null);
			p.getRentInfo().setPurposes(null);
			p.getRentInfo().getPersonalcarport().getLandlady().setPersonalcarport(null);
			p.getRentInfo().getPersonalcarport().getLandlady().setUser(null);
			p.getRenter().setPurposes(null);
		}
		return page;
		
	}
	@RequestMapping(path="cbd/landlady/getRecordInfo")
	public @ResponseBody Record getRecordInfo(String recordID){
		Record r = recordService.findRecordById(Integer.parseInt(recordID));
		Purpose p = r.getPurpose();
		p.setRecord(null);
		p.getRenter().setPurposes(null);
		p.getRenter().setUser(null);
		p.getRentInfo().setPurposes(null);
		p.getRentInfo().getPersonalcarport().setLandlady(null);
		return r;
		
	}
	@RequestMapping(path="cbd/landlady/ladyComplaint")
	public@ResponseBody int ladyComplaint(String reason,String recordID){
		Complaintrecord c = new Complaintrecord();
		c.setReason(reason);
		Record r = new Record();
		r.setRecordID(Integer.parseInt(recordID));
		Date d = new Date();
		c.setTime(d);
		c.setComplaint(true);
		c.setType(false);
		c.setRecord(r);
		return cs.addComplaintrecord(c);
		
	}
	@RequestMapping(path="cbd/landlady/checkIsComplaint")
	public @ResponseBody int checkIsComplaint(String recordID){
		int num = cs.checkIsCompalint(Integer.parseInt(recordID));
		return num;
		
	}
	@RequestMapping(path="cbd/landlady/removeLady")
	public void removeLady(HttpServletRequest req,PrintWriter pw){
		req.getSession().removeAttribute("myLandLady");
		req.getSession().removeAttribute("login");
		pw.write("");
		
	}
	
}
